
/**
 * Content: Semaphore信号量
 * --------------------------------------------------
 * Java并发工具之Semaphore: https://blog.csdn.net/weixin_41951205/article/details/123193171
 */

import java.util.concurrent.Semaphore;

public class java_1120_Semaphore {
    public static void main(String[] args) {

        // Semaphore信号量
        System.out.println("--------------------Semaphore信号量--------------------");

        // 信号量, 值为 1
        Semaphore semaphore = new Semaphore(1);

        Thread thread1 = new MyThreadA(semaphore);
        Thread thread2 = new MyThreadA(semaphore);

        // 给线程设置名称
        thread1.setName("XQZ-Thread-OOO");
        thread2.setName("XQZ-Thread-XXX");

        // 启动线程
        thread1.start();
        thread2.start();

    }
}

// 创建线程方式一
class MyThreadA extends Thread {
    static int sign = 1;

    Semaphore semaphore;

    public MyThreadA(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        while (true) {
            try {
                // 获取信号量
                semaphore.acquire();
                for (int i = 1; i <= 5; ++i) {
                    System.out.println(Thread.currentThread().getName() + "---" + sign++);
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放信号量
                semaphore.release();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}